package com.walk.zworld.ui

import android.Manifest
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.core.content.PermissionChecker.PERMISSION_GRANTED
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.base.lib.base.utils.ToastUtil
import com.base.lib.base.view.BaseActivity
import com.base.lib.common.utils.DateUtil
import com.base.lib.common.utils.SPUtils
import com.base.lib.common.utils.SdkVersionUtil
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.walk.zworld.BuildConfig
import com.walk.zworld.R
import com.walk.zworld.api.bean.ConfigBean
import com.walk.zworld.api.http.CommonAppConfig
import com.walk.zworld.api.utils.WordUtil
import com.walk.zworld.receiver.NetworkChangeReceiver
import com.walk.zworld.ui.activity.MyDetailActivity
import com.walk.zworld.ui.fragment.*
import com.walk.zworld.ui.location.LocationDetailFragment
import com.walk.zworld.utils.DialogUitl
import com.walk.zworld.utils.PermissionUtils
import com.walk.zworld.utils.observer.DefaultObserver
import com.walk.zworld.webView.WebViewActivity.Companion.start
import kotlin.system.exitProcess


/**
 * 版本1.0
 * 2020-12-23.
 */
class Main1Activity : BaseActivity() {

    companion object {
        const val REQ_CODE_INIT_API_KEY = 666
    }

    override fun onBindLayout(): Int = R.layout.activity_main

    /**
     * 网络状态变化的广播
     */
    private var mNetworkChangeReceiver: NetworkChangeReceiver? = null

    //定义是否退出程序的标记
    private var isExit = 0L
    private lateinit var viewPager: ViewPager
    private lateinit var titleList: MutableList<String>
    private lateinit var titleResList: MutableList<Int>
    private var pos = 0

    /**
     * 权限申请
     */
    private val permissionArray = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        /* Manifest.permission.WRITE_SECURE_SETTINGS,*/
    )
    private var mPermissionList = arrayListOf<String>()
    private lateinit var mPermissionDialog: AlertDialog

    /**
     * newInstance并不能保证fragment是同一个，可能会重新new一个，所以这里设置一下
     */
    private val locationDetailFragment = LocationDetailFragment.newsInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        overridePendingTransition(
            android.R.anim.fade_in,
            android.R.anim.fade_out
        )
        setTopTitle("首页")
//        setLeft(R.mipmap.ic_fly) { startActivity(Intent(this, SquarePageActivity::class.java)) }
        setRight("我的") {
            if (!CommonAppConfig.isLogin()) {
                ToastUtil.showToast("完成设备信息绑定后才可使用'我的'功能")
                return@setRight
            }
            startActivity(Intent(this, MyDetailActivity::class.java))
        }
        setLeft("帮助文档") {
            start(it.context, "http://web.nowk.top//appapi/page/detail?id=4")
        }

        if (!(SPUtils.get(baseContext, "todaty_first_update_"+DateUtil.getToday(), false) as Boolean)) {
            CommonAppConfig.getObserverConfig().subscribe(object : DefaultObserver<ConfigBean?>() {
                override fun onError(e: Throwable) {
                    super.onError(e)
                    Toast.makeText(mContext, "无法连接服务器,请检查网络设置", Toast.LENGTH_SHORT).show()
                    Thread.sleep(1000)
                    exitProcess(0)
                }
                override fun onNext(configBean: ConfigBean) {
                    if (SdkVersionUtil.getAppVersion(mContext) < configBean.version.toInt()) {
                        val builder: DialogUitl.Builder = DialogUitl.Builder(mContext)
                        val build = builder.setTitle(WordUtil.getString(R.string.version_update))
                            .setContent("检测到有新版本可用，请立即更新")
                            .setConfrimString(WordUtil.getString(R.string.version_immediate_use))
                            .setCancelString(WordUtil.getString(R.string.version_not_update))
                            .setCancelable(configBean.forceUpdate == 1)
                            .setClickCallback(object : DialogUitl.SimpleCallback {
                                override fun onConfirmClick(dialog: Dialog?, content: String?) {
                                    if (!TextUtils.isEmpty(configBean.downloadApkUrl)) {
                                        openBrowser(baseContext, configBean.downloadApkUrl)
                                    } else {
                                        ToastUtil.showToast(R.string.version_download_url_error)
                                    }
                                }
                                override fun onCancelClick() {
                                    if (configBean.forceUpdate == 1) {
                                        exitProcess(0)
                                    } else {
                                        val today = DateUtil.getToday();
                                        SPUtils.put(baseContext, "todaty_first_update_$today", true);
                                    }
                                }
                            })
                            .build()
                        build.show()
                    }
                }
            })
        }
        if (SPUtils.get(baseContext, "first_open_app", true) as Boolean) {
            val builder: DialogUitl.Builder = DialogUitl.Builder(mContext)
            val build = builder.setTitle("提示")
                .setContent("欢迎使用模拟定位试用1.0\n更多功能敬请期待")
                .setConfrimString("我知道了")
                .build()
            build.show()
            SPUtils.put(baseContext, "first_open_app", false)
        }
    }

    fun openBrowser(context: Context, url: String?) {
        val intent = Intent()
        intent.action = Intent.ACTION_VIEW
        intent.data = Uri.parse(url)
        context.startActivity(intent)
    }

    override fun initData() {
        initPermission()
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
    }

    private fun initPermission() {
        mPermissionList.clear()//清空没有通过的权限
        for (i in permissionArray.indices) {
            if (!PermissionUtils.checkPhonePermission(this, permissionArray[i]))
                mPermissionList.add(permissionArray[i])
        }
        if (mPermissionList.size > 0) PermissionUtils.requestPermissions(
            this, permissionArray,
            REQ_CODE_INIT_API_KEY
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        var hasPermissionDismiss = false
        if (requestCode == REQ_CODE_INIT_API_KEY) {
            for (i in grantResults.indices) {
                if (grantResults[i] != PERMISSION_GRANTED) {
                    hasPermissionDismiss = true
                    ToastUtil.showToast(permissions.get(i) + " 没给");
                }
            }
            if (hasPermissionDismiss) showPermissionDialog()
        }
    }

    private fun showPermissionDialog() {
        if (!this::mPermissionDialog.isInitialized) {
            mPermissionDialog = AlertDialog.Builder(this)
                .setMessage("权限申请失败")
                .setPositiveButton("去设置") { _, _ ->
                    mPermissionDialog.dismiss()
                    //跳转到应用设置
                    val packageURI = Uri.parse("package:${BuildConfig.APPLICATION_ID}")
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI)
                    startActivity(intent)
                    this.finish()
                }
                .setNegativeButton("取消") { _, _ ->
                    mPermissionDialog.dismiss()
//                    this.finish()
                }
                .setCancelable(false)
                .create()
            mPermissionDialog.show()
        }
    }

    override fun initView() {
        titleResList = mutableListOf()
        titleResList.run { add(R.id.navigation_home) }
        //初始化ViewPager
        initViewPager()
        findViewById<BottomNavigationView>(R.id.bottom_bar).setOnNavigationItemSelectedListener {
            viewPager.currentItem = titleResList.indexOf(it.itemId);
            return@setOnNavigationItemSelectedListener true
        }
    }

    private fun initViewPager() {
        titleList = mutableListOf()
        titleList.run { add("首页") }
        //初始化ViewPager,这是只能用viewPager，不能用viewPager2。2会滑动冲突，不好解决
        viewPager = findViewById<ViewPager>(R.id.vp2_fragment)
        val bottom_bar = findViewById<BottomNavigationView>(R.id.bottom_bar)
        bottom_bar.visibility = View.GONE
        val bottom_fab = findViewById<FloatingActionButton>(R.id.bottom_fab)
        bottom_fab.visibility = View.GONE
        viewPager.run {
            adapter = MainPagerAdapter()
            //解决滑动页面后再回来会刷新页面的问题，因为viewPager默认只预加载一页，多的页面会回收
            offscreenPageLimit = 1
            addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {
                }

                @SuppressLint("WrongConstant")
                override fun onPageSelected(position: Int) {
                    pos = position
                    mToolbar?.visibility = View.VISIBLE
                    setTopTitle(titleList[position])
                    bottom_bar.selectedItemId = titleResList[position]
                    bottom_fab.setImageResource(if (0==position) R.mipmap.ic_home_select else R.mipmap.ic_home)
                }

                override fun onPageScrollStateChanged(state: Int) {}
            })
            viewPager.currentItem = pos
            bottom_fab.setImageResource(if (0==pos) R.mipmap.ic_home_select else R.mipmap.ic_home)
        }
    }

    inner class MainPagerAdapter : FragmentPagerAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
        override fun getCount(): Int = 1
        override fun getItem(position: Int): Fragment { return locationDetailFragment }
    }

    override fun onResume() {
        // 动态注册网络变化广播
        val filter = IntentFilter()
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
        mNetworkChangeReceiver = NetworkChangeReceiver()
        registerReceiver(mNetworkChangeReceiver, filter)
        super.onResume()
    }

    override fun onPause() {
        if (mNetworkChangeReceiver != null) {
            unregisterReceiver(mNetworkChangeReceiver)
            mNetworkChangeReceiver = null
        }
        super.onPause()
    }

    var makeText: Toast? = null;
    @SuppressLint("ShowToast")
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        //判断用户是否点击的是返回键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //如果用户没有在2秒内再次按返回键的话，标记用户为不退出状态
            if (System.currentTimeMillis() - isExit <= 2000 || isFinishing) {
                makeText?.cancel()
                //退出程序
                onBackPressedDispatcher.onBackPressed()
            } else {
                isExit = System.currentTimeMillis()
                makeText = Toast.makeText(mContext, "再按一次退出应用", Toast.LENGTH_SHORT)
                makeText?.show();
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}